#!D:\Python27\python.exe
# -*- coding: utf-8 -*-
'''
    Implements abstract command

    :copyright: (c) 2014 by Duxin.
'''

import cgi
import Cookie
import os

import config
import sessions
import db.db_manager as dbm

class Command(object):
    '''
        Command is the base class of all specical Commands. This class can deal with the session
        and parameter problems. So the derived class can foues on their own logical.
        Any derived class must implements two interfaces: 1. is_param_right, which is responsible 
        for parameter checking. 2. execute, which is responsible for doing some specical task.
    '''
    
    def __init__(self):
        self.form = cgi.FieldStorage()
       
        cookie = Cookie.SimpleCookie()
        string_cookie = os.environ.get('HTTP_COOKIE')
        
        session = None
        
        # If already existent session
        if string_cookie:
            cookie.load(string_cookie)
            sid = cookie['sid'].value
            session = sessions.Session.get_session(sid)
            cookie['sid']['path'] = '/'
        
        self.session = session
        self.cookie = cookie
        
        self.cgi_body = ''
    
    def __del__(self):
        dbm.SessionDAO.persist(self.session)
    
    def get_session(self):
        if self.session is None:
            self.session = sessions.Session()
            # Set the sid in the cookie
            self.cookie['sid'] = self.session.get_session_id()
            # Will expire in one week
            self.cookie['sid']['expires'] = config.cookie.expire_time
            self.cookie['sid']['path'] = '/'
        
        return self.session
    
    def get_param(self, key):
        form = cgi.FieldStorage()
        
        if form.has_key(key):
            return form[key].value 
        else:
            return None

    def write(self, str):        
        self.cgi_body = "%s%s"%(self.cgi_body, str)
    
    def output(self):
        print self.cookie
        print 'Content-type: text/html\n\n'
        print self.cgi_body

    def is_param_right(self):
        pass
    
    def execute(self):
        raise RuntimeException("not implemented")
